/**
 * Created by jiangzhiyong on 15/10/14.
 */

var Manage = {
    init : function() {
        Manage.get_data();
        $("#data_table tbody").find("a[name='update_class']").click(Manage.class_show);
        $("a[name='add_class']").click(Manage.class_show);
        $("#do_update_class").click(function(){
        		var class_id = $("#update_class").find("input[name='class_id']").val();
        		var class_name = $("#update_class").find("input[name='class_name']").val();
        		if (class_name == null || class_name == "") {
        			alert("科目名称不能为空");
        			return false;
        		}
        		if(class_id == "" || class_id == 0) {
        			//新增
        			ajax("/classes/create", {"name" : class_name}, success);
        		} else {
        			//编辑
        			ajax("/classes/update", {"class_id": class_id, "name" : class_name}, success);
        		}
        });
    },
    get_data : function() {
        var data = {};
        ajax("/classes/list", data, callback);
    },
    class_show : function() {
    		var class_id = $(this).attr("class_id");
    		$("#update_class").find("input[name='class_id']").val(class_id);
    		var class_name = $(this).attr("class_name");
    		$("#update_class").find("input[name='class_name']").val(class_name);
    		$("#update_class").modal('show');
    },
    init_table : function(result) {
    		if (result != null && result.data != null && result.data.classes.length > 0) {
    			var tbody = $("#data_table tbody");
    			tbody.empty();
    			var classes = result.data.classes;
    			var trs = "";
    			for (var i=0; i < classes.length; i++) {
    				var classOne = classes[i];
    				trs += ("<tr>");
    				var className = ("<td>" + classOne.name +"</td>");
    				var classStatus = ("<td>正常</td>");
    				trs += (className + classStatus);
    				trs += ("</tr>");
    			}
    			if (classes.length == 0) {
				trs += ("<tr>");
				trs += ("<td colspan='2'>未查询到任何结果</td>");
				trs += ("</tr>");
			}
    			tbody.append(trs);
    			
    		}
    }
};

function callback(result) {
	Manage.init_table(result);
}

function success(result) {
	if (result != null && result.code == 0) {
		window.location.reload();
	} else {
		alert("操作失败，请刷新页面重试！");
	}
}

$(function(){
    Manage.init();
})
